package com.tool4j.sse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/sse/event")
@Slf4j
public class SseEventController {

    @Autowired
    private SseEventPublisher eventPublisher;

    @GetMapping(value = "/connect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> connect(@RequestParam String clientId) {
        return eventPublisher.getEventFlux(clientId)
                .doOnSubscribe(subscription -> {
                })
                .doOnCancel(() -> {
                    eventPublisher.removeClient(clientId);
                })
                .doOnTerminate(() -> {
                    eventPublisher.removeClient(clientId);
                })
                .doOnError(throwable -> {
                    log.error("SSE 连接出错: {}, 错误: {}", clientId, throwable.getMessage());
                    eventPublisher.removeClient(clientId);
                })
                .map(data -> ServerSentEvent.<String>builder()
                        .data(data)
                        .build());
    }

}
